<template>
  <div class="content-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">公告运营平台</h1>
        <p class="page-description">创建、编辑和管理系统公告内容</p>
      </div>
      <div class="page-actions">
        <el-button type="primary" size="large" @click="createNewAnnouncement">
          <el-icon><Plus /></el-icon> 新建公告
        </el-button>
        <el-button size="large" @click="refreshAnnouncements">
          <el-icon><RefreshRight /></el-icon> 刷新
        </el-button>
      </div>
    </div>
    
    <!-- 编辑器区域 -->
    <div class="row-container" v-if="showEditor">
      <el-card class="editor-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <div class="card-title">
              {{ isEditing ? '编辑公告 - ' + announcementForm.title : '新建公告' }}
            </div>
            <div class="editor-actions">
              <el-button type="primary" @click="publishContent">
                <el-icon><Upload /></el-icon> {{ isEditing ? '更新' : '发布' }}
              </el-button>
              <el-button type="success" @click="saveDraft">
                <el-icon><Document /></el-icon> 保存草稿
              </el-button>
              <el-button @click="previewContent">
                <el-icon><View /></el-icon> 预览
              </el-button>
              <el-button type="info" @click="cancelEdit">
                <el-icon><Close /></el-icon> 取消
              </el-button>
            </div>
          </div>
        </template>
        
        <div class="form-section">
          <el-form :model="announcementForm" :rules="rules" ref="announcementForm" label-width="100px" class="announcement-form">
            <el-form-item label="公告标题" prop="title" class="form-item">
              <el-input v-model="announcementForm.title" placeholder="请输入公告标题"></el-input>
            </el-form-item>
            
            <el-form-item label="有效期间" class="form-item">
              <el-date-picker
                v-model="dateRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="handleDateChange"
                class="date-picker"
              ></el-date-picker>
            </el-form-item>
            
            <el-form-item label="优先级" prop="priority" class="form-item">
              <el-select v-model="announcementForm.priority" placeholder="请选择优先级" class="priority-select">
                <el-option :value="0" label="普通" class="priority-normal"></el-option>
                <el-option :value="1" label="重要" class="priority-important"></el-option>
                <el-option :value="2" label="紧急" class="priority-urgent"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="是否启用" prop="is_active" class="form-item">
              <el-switch 
                v-model="announcementForm.is_active"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="启用"
                inactive-text="禁用"
              ></el-switch>
            </el-form-item>
          </el-form>
        </div>
        
        <div class="editor-wrapper">
          <div class="editor-section">
            <div class="section-title">公告内容</div>
            <el-form-item prop="content">
              <el-input
                type="textarea"
                :rows="15"
                placeholder="请输入公告内容"
                v-model="announcementForm.content"
                class="content-textarea"
              ></el-input>
            </el-form-item>
          </div>
          
          <div class="preview-section">
            <div class="preview-header">
              <div class="preview-title">预览</div>
            </div>
            <div class="preview-content">
              <h2 class="preview-title-text">{{ announcementForm.title || '公告标题' }}</h2>
              <div class="preview-meta">
                <div class="meta-item">
                  <el-icon><Calendar /></el-icon>
                  <span>有效期: {{ dateRange && dateRange.length ? `${dateRange[0]} 至 ${dateRange[1]}` : '未设置' }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><StarFilled /></el-icon>
                  <span>优先级: </span>
                  <el-tag :type="getPriorityType(announcementForm.priority)" size="small">
                    {{ getPriorityText(announcementForm.priority) }}
                  </el-tag>
                </div>
                <div class="meta-item">
                  <el-icon><SwitchButton /></el-icon>
                  <span>状态: </span>
                  <el-tag :type="announcementForm.is_active ? 'success' : 'danger'" size="small">
                    {{ announcementForm.is_active ? '启用' : '禁用' }}
                  </el-tag>
                </div>
              </div>
              <div class="preview-body" v-html="contentPreview"></div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 公告列表区域 -->
    <div class="row-container">
      <el-card class="table-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <div class="card-title">公告列表</div>
            <div class="list-actions">
              <el-button type="primary" @click="applyFilters" size="default">
                <el-icon><Search /></el-icon> 查询
              </el-button>
              <el-button @click="resetFilters" size="default">
                <el-icon><Refresh /></el-icon> 重置
              </el-button>
            </div>
          </div>
        </template>
        
        <!-- 筛选器 -->
        <div class="filters-section">
          <div class="filter-row">
            <div class="search-bar">
              <div class="filter-group search-group">
                <el-input 
                  v-model="searchQuery" 
                  placeholder="搜索公告标题或内容"
                  class="search-input"
                  clearable
                  @keyup.enter="applyFilters"
                  @input="onSearchInput"
                  @clear="handleSearchClear"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                  <template #suffix v-if="searchQuery">
                    <el-button class="clear-search" circle size="small" @click="handleSearchClear">
                      <el-icon><Close /></el-icon>
                    </el-button>
                  </template>
                </el-input>
                <el-button class="advanced-toggle" type="text" @click="showAdvanced = !showAdvanced">
                  {{ showAdvanced ? '收起高级搜索' : '高级搜索' }}
                  <el-icon class="toggle-icon" :class="{ 'is-active': showAdvanced }">
                    <ArrowDown />
                  </el-icon>
                </el-button>
              </div>
            </div>
            
            <div v-if="showAdvanced" class="advanced-search">
              <div class="filter-options">
                <div class="filter-group">
                  <span class="filter-label">状态：</span>
                  <el-select v-model="statusFilter" placeholder="选择状态" clearable class="filter-select" @change="handleFilterChange">
                    <el-option label="全部" value=""></el-option>
                    <el-option label="启用" value="true"></el-option>
                    <el-option label="禁用" value="false"></el-option>
                  </el-select>
                </div>
                <div class="filter-group">
                  <span class="filter-label">优先级：</span>
                  <el-select 
                    v-model="priorityFilter" 
                    placeholder="选择优先级" 
                    clearable 
                    class="filter-select"
                    @change="handleFilterChange"
                  >
                    <el-option label="全部" :value="null"></el-option>
                    <el-option label="普通" :value="0"></el-option>
                    <el-option label="重要" :value="1"></el-option>
                    <el-option label="紧急" :value="2"></el-option>
                  </el-select>
                </div>
              </div>

              <div class="filter-actions">
                <el-button type="primary" @click="applyFilters">
                  <el-icon><Search /></el-icon> 查询
                </el-button>
                <el-button @click="resetFilters">
                  <el-icon><Refresh /></el-icon> 重置
                </el-button>
                <el-button v-if="hasSearchHistory" type="info" @click="showSearchHistory = true">
                  <el-icon><Timer /></el-icon> 搜索历史
                </el-button>
              </div>
            </div>
            
            <!-- 搜索提示与标签显示 -->
            <div v-if="hasActiveFilters" class="active-filters">
              <div class="filter-hint">搜索条件：</div>
              <div class="filter-tags">
                <el-tag v-if="searchQuery" closable @close="searchQuery = ''; applyFilters()">
                  关键词: {{ searchQuery }}
                </el-tag>
                <el-tag v-if="statusFilter !== null" closable @close="statusFilter = null; applyFilters()">
                  状态: {{ statusFilter === 'true' ? '启用' : '禁用' }}
                </el-tag>
                <el-tag v-if="priorityFilter !== null && priorityFilter !== undefined" closable @close="priorityFilter = null; applyFilters()">
                  优先级: {{ getPriorityText(priorityFilter) }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 表格 -->
        <el-table 
          :data="paginatedAnnouncements" 
          style="width: 100%" 
          v-loading="loading"
          :header-cell-style="{backgroundColor: '#f5f7fa', color: '#303133', fontWeight: '600'}"
          class="announcement-table"
        >
          <el-table-column prop="title" label="标题" show-overflow-tooltip min-width="200"></el-table-column>
          <el-table-column label="优先级" width="100">
            <template #default="{ row }">
              <el-tag :type="getPriorityType(row.priority)" effect="dark" size="small">
                {{ getPriorityText(row.priority) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.is_active ? 'success' : 'danger'" effect="dark" size="small">
                {{ row.is_active ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="有效期" width="260" label-class-name="valid-period-header">
            <template #default="{ row }">
              <div class="date-range-column">
                <el-icon><Timer /></el-icon>
                <div class="date-text">{{ formatDateTime(row.start_at) }}</div>
                <div class="date-separator">至</div>
                <div class="date-text">{{ formatDateTime(row.end_at) }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="create_at" label="创建时间" width="150">
            <template #default="{ row }">
              <div class="create-time">
                <el-icon><Calendar /></el-icon>
                <span>{{ row.create_at }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250">
            <template #default="{ row }">
              <div class="table-actions">
                <el-button type="primary" size="small" @click="editContent(row)">
                  <el-icon><Edit /></el-icon> 编辑
                </el-button>
                <el-button type="info" size="small" @click="previewContent(row)">
                  <el-icon><View /></el-icon> 预览
                </el-button>
                <el-button type="danger" size="small" @click="deleteContent(row)">
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
              </div>
            </template>
          </el-table-column>
          <template #empty>
            <div class="empty-data">
              <el-empty :image-size="100" description="暂无公告数据">
                <template #description>
                  <p>{{ hasActiveFilters ? '没有找到符合条件的公告' : '暂无公告数据' }}</p>
                  <div v-if="hasActiveFilters" class="empty-actions">
                    <el-button type="primary" @click="resetFilters" size="small">清除筛选</el-button>
                  </div>
                </template>
              </el-empty>
            </div>
          </template>
        </el-table>
        
        <div class="pagination">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            v-model:current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            background
          ></el-pagination>
        </div>
      </el-card>
    </div>
    
    <!-- 浮动操作区 -->
    <div class="floating-actions">
      <el-button type="primary" @click="refreshAnnouncements" :loading="loading" class="refresh-btn">
        <el-icon><RefreshRight /></el-icon>
      </el-button>
    </div>
    
    <!-- 底部安全区域 -->
    <div class="bottom-safe-area"></div>
    
    <!-- 搜索历史弹窗 -->
    <el-dialog title="搜索历史" v-model="showSearchHistory" width="500px">
      <div v-if="searchHistory.length" class="search-history-list">
        <div v-for="(item, index) in searchHistory" :key="index" class="search-history-item">
          <div class="history-content" @click="applyHistorySearch(item)">
            <el-icon><Search /></el-icon>
            <div class="history-text">
              <span v-if="item.searchQuery" class="history-keyword">{{ item.searchQuery }}</span>
              <span v-if="item.statusFilter !== ''" class="history-filter">状态: {{ item.statusFilter === 'true' ? '启用' : '禁用' }}</span>
              <span v-if="item.priorityFilter !== null && item.priorityFilter !== undefined" class="history-filter">优先级: {{ getPriorityText(item.priorityFilter) }}</span>
            </div>
          </div>
          <el-button type="danger" size="small" circle @click="removeSearchHistory(index)">
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
      </div>
      <div v-else class="empty-history">
        <el-empty description="暂无搜索历史" :image-size="80"></el-empty>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showSearchHistory = false">取消</el-button>
          <el-button type="danger" @click="clearSearchHistory">清空历史</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { 
  Plus, 
  RefreshRight, 
  Upload, 
  Document, 
  View, 
  Close, 
  Search, 
  Refresh,
  Calendar,
  Timer,
  StarFilled,
  SwitchButton,
  Edit,
  Delete,
  ArrowDown
} from '@element-plus/icons-vue'

export default {
  name: 'ContentPage',
  components: {
    Plus,
    RefreshRight,
    Upload,
    Document,
    View,
    Close,
    Search,
    Refresh,
    Calendar,
    Timer,
    StarFilled,
    SwitchButton,
    Edit,
    Delete,
    ArrowDown
  },
  data() {
    return {
      showEditor: false,
      isEditing: false,
      currentAnnouncementId: null,
      dateRange: [],
      loading: false,
      contentPreview: '',
      searchQuery: '',
      statusFilter: null,
      priorityFilter: null,
      showAdvanced: false,
      searchTimer: null,
      searchHistory: [],
      showSearchHistory: false,
      currentPage: 1,
      pageSize: 10,
      pagination: {
        total: 0,
        totalPages: 0
      },
      contentList: [],
      announcementForm: {
        title: '',
        content: '',
        start_at: '',
        end_at: '',
        is_active: true,
        priority: 0
      },
      rules: {
        title: [
          { required: true, message: '请输入公告标题', trigger: 'blur' },
          { max: 100, message: '标题长度不能超过100个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入公告内容', trigger: 'blur' }
        ]
      },
      originalAnnouncements: []
    }
  },
  computed: {
    // 计算筛选后的公告列表
    filteredAnnouncements() {
      return this.contentList;
    },
    // 判断是否有活跃的筛选条件
    hasActiveFilters() {
      return this.searchQuery || 
             this.statusFilter !== null || 
             this.priorityFilter !== null;
    },
    // 判断是否有搜索历史
    hasSearchHistory() {
      return this.searchHistory && this.searchHistory.length > 0;
    },
    // 计算当前页数据
    paginatedAnnouncements() {
      // 使用服务器返回的当前页数据
      return this.contentList;
    }
  },
  created() {
    this.loadSearchHistory();
    this.fetchAnnouncements();
  },
  methods: {
    async fetchAnnouncements() {
      this.loading = true;
      try {
        // 构建API请求参数
        const params = {
          page: this.currentPage || 1,
          page_size: this.pageSize || 10
        };
        
        // 添加筛选条件
        if (this.statusFilter !== null && this.statusFilter !== '') {
          params.is_active = this.statusFilter === 'true';
        }
        
        // 添加优先级筛选
        if (this.priorityFilter !== null && this.priorityFilter !== undefined) {
          params.priority = this.priorityFilter;
        }
        
        // 添加搜索关键词
        if (this.searchQuery && this.searchQuery.trim()) {
          params.keyword = this.searchQuery.trim();
        }
        
        console.log('获取公告列表参数:', params);
        
        // 构建请求头，添加认证信息
        const headers = {
          'Content-Type': 'application/json'
          // 如果需要认证，可以添加 'Authorization': 'Bearer ' + token
        };
        
        // 创建请求配置
        const requestConfig = {
          params,
          headers,
          timeout: 10000, // 10秒超时
        };
        
        // 发送API请求
        try {
          const response = await axios.get('https://smartsound.top/api/admin/v1/announcements', requestConfig);
          
          // 处理API响应
          if (response.data.code === 0) {
            // 存储原始数据
            const announcements = response.data.data.announcements || [];
            
            // 更新分页信息
            this.pagination = {
              total: response.data.data.total || 0,
              totalPages: response.data.data.total_pages || 0
            };
            
            // 更新当前页码
            if (response.data.data.page) {
              this.currentPage = response.data.data.page;
            }
            
            // 保存列表数据
            this.storeOriginalData(announcements);
            
            console.log(`成功获取${announcements.length}条公告数据，总数: ${this.pagination.total}`);
          } else {
            console.error('API错误:', response.data);
            this.$message.error(response.data.message || '获取公告列表失败');
            
            // 如果是认证错误，可以使用模拟数据
            if (response.data.code === 40101) {
              this.useMockData();
            }
          }
        } catch (apiError) {
          console.error('API请求失败:', apiError);
          
          // 服务器错误时使用模拟数据
          this.$message.error('服务器暂时不可用，显示本地缓存数据');
          this.useMockData();
        }
      } catch (error) {
        console.error('获取公告列表失败:', error);
        this.$message.error('获取公告列表失败');
        this.useMockData();
      } finally {
        this.loading = false;
      }
    },
    
    // 使用模拟数据，当API不可用时
    useMockData() {
      console.log('使用模拟数据');
      const mockAnnouncements = [
        {
          announcement_id: 'mock-1',
          title: '系统维护通知',
          content: '系统将于本周六晚上10点至周日凌晨2点进行维护升级，期间系统将不可用。',
          priority: 2,
          is_active: true,
          start_at: '2025-05-28 00:00:00',
          end_at: '2025-06-04 23:59:59',
          create_at: '2025-05-27 15:30:00',
          update_at: '2025-05-27 15:30:00',
          admin_name: '系统管理员'
        },
        {
          announcement_id: 'mock-2',
          title: '新功能发布公告',
          content: '我们很高兴地通知大家，系统已经更新了一系列新功能，包括...',
          priority: 1,
          is_active: true,
          start_at: '2025-05-20 00:00:00',
          end_at: '2025-06-20 23:59:59',
          create_at: '2025-05-20 09:15:00',
          update_at: '2025-05-20 09:15:00',
          admin_name: '产品经理'
        },
        {
          announcement_id: 'mock-3',
          title: '使用指南更新',
          content: '系统使用指南已更新，请点击此处查看最新版本...',
          priority: 0,
          is_active: true,
          start_at: '2025-05-15 00:00:00',
          end_at: '2025-07-15 23:59:59',
          create_at: '2025-05-15 14:20:00',
          update_at: '2025-05-15 14:20:00',
          admin_name: '技术支持'
        },
        {
          announcement_id: 'mock-4',
          title: '过期公告测试',
          content: '这是一条已过期的公告，用于测试过期状态的显示效果。',
          priority: 0,
          is_active: false,
          start_at: '2025-04-01 00:00:00',
          end_at: '2025-05-01 23:59:59',
          create_at: '2025-04-01 10:00:00',
          update_at: '2025-04-01 10:00:00',
          admin_name: '测试账号'
        }
      ];
      
      this.storeOriginalData(mockAnnouncements);
    },
    createNewAnnouncement() {
      this.isEditing = false;
      this.currentAnnouncementId = null;
      
      // 设置默认日期范围为今天和一个月后
      const today = new Date();
      const nextMonth = new Date();
      nextMonth.setMonth(nextMonth.getMonth() + 1);
      
      this.announcementForm = {
        title: '',
        content: '',
        start_at: '',
        end_at: '',
        is_active: true,
        priority: 0
      };
      this.dateRange = [today, nextMonth];
      
      // 手动触发日期变更处理
      this.handleDateChange(this.dateRange);
      
      this.contentPreview = '';
      this.showEditor = true;
    },
    handleDateChange(val) {
      console.log('日期选择器值变更:', val);
      if (val && val.length === 2) {
        // 格式化日期
        const formatDate = (date) => {
          if (typeof date === 'string') return date;
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          const hours = String(date.getHours()).padStart(2, '0');
          const minutes = String(date.getMinutes()).padStart(2, '0');
          const seconds = String(date.getSeconds()).padStart(2, '0');
          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        };
        
        this.announcementForm.start_at = formatDate(val[0]);
        this.announcementForm.end_at = formatDate(val[1]);
        console.log('日期范围已更新:', this.announcementForm.start_at, this.announcementForm.end_at);
      } else {
        this.announcementForm.start_at = '';
        this.announcementForm.end_at = '';
        console.log('日期范围已清空');
      }
    },
    cancelEdit() {
      this.showEditor = false;
    },
    async publishContent() {
      // 表单验证
      if (!this.$refs.announcementForm) {
        this.$message.warning('表单未加载完成，请稍后再试');
        return;
      }
      
      let valid = false;
      try {
        valid = await new Promise(resolve => {
          this.$refs.announcementForm.validate(isValid => {
            resolve(isValid);
          });
        });
      } catch (e) {
        console.error('表单验证出错', e);
        valid = false;
      }
      
      if (!valid) {
        this.$message.warning('请填写完整的公告信息');
        return;
      }
      
      // 检查日期范围
      if (!this.dateRange || !Array.isArray(this.dateRange) || this.dateRange.length < 2) {
        this.$message.warning('请设置公告的有效期');
        return;
      }
      
      // 确保日期正确设置到表单中
      if (!this.announcementForm.start_at || !this.announcementForm.end_at) {
        this.handleDateChange(this.dateRange);
      }
      
      // 提交公告
      if (this.isEditing && this.currentAnnouncementId) {
        await this.updateAnnouncement();
      } else {
        await this.submitAnnouncement();
      }
    },
    async updateAnnouncement() {
      // 确保priority是数字类型
      const formData = {
        ori_announcements_id: this.currentAnnouncementId,
        title: this.announcementForm.title,
        content: this.announcementForm.content,
        start_at: this.announcementForm.start_at,
        end_at: this.announcementForm.end_at,
        is_active: this.announcementForm.is_active,
        priority: Number(this.announcementForm.priority)
      };
      
      console.log('更新公告数据:', formData);
      
      try {
        // 调用更新公告的API
        const response = await axios.post(
          'https://smartsound.top/api/admin/v1/announcements/update', 
          formData
        );
        
        if (response.data.code === 0) {
          this.$message.success('公告更新成功');
          this.showEditor = false;
          this.fetchAnnouncements(); // 刷新列表
        } else {
          this.$message.error(response.data.message || '公告更新失败');
        }
      } catch (error) {
        console.error('更新公告失败:', error);
        if (error.response) {
          console.error('错误响应:', error.response.data);
          this.$message.error(`更新公告失败: ${error.response.data.message || '未知错误'}`);
        } else {
          this.$message.error('更新公告失败，请检查网络连接');
        }
      }
    },
    async submitAnnouncement() {
      // 确保priority是数字类型
      const formData = {
        ...this.announcementForm,
        priority: Number(this.announcementForm.priority)
      };
      
      console.log('发送公告数据:', formData);
      
      try {
        // 调用创建公告的API
        const response = await axios.post('https://smartsound.top/api/admin/v1/announcements', formData);
        
        if (response.data.code === 0) {
          this.$message.success('公告发布成功');
          this.showEditor = false;
          this.fetchAnnouncements(); // 刷新列表
        } else {
          this.$message.error(response.data.message || '公告发布失败');
        }
      } catch (error) {
        console.error('发布公告失败:', error);
        if (error.response) {
          console.error('错误响应:', error.response.data);
          this.$message.error(`发布公告失败: ${error.response.data.message || '未知错误'}`);
        } else {
          this.$message.error('发布公告失败，请检查网络连接');
        }
      }
    },
    saveDraft() {
      if (!this.announcementForm.title.trim() || !this.announcementForm.content.trim()) {
        this.$message.warning('请填写公告标题和内容');
        return;
      }
      
      this.$message.success('草稿保存成功');
      // 本地存储草稿功能可以在这里实现
    },
    previewContent(item) {
      if (item) {
        // 如果传入了公告项，则获取详情
        this.fetchAnnouncementDetail(item.announcement_id, 'preview');
      } else {
        // 否则直接预览当前编辑中的内容
        this.contentPreview = this.announcementForm.content;
      }
    },
    async editContent(item) {
      // 如果是模拟数据，显示提示
      if (item.announcement_id && typeof item.announcement_id === 'string' && item.announcement_id.startsWith('mock-')) {
        this.$message({
          message: '演示环境不支持编辑操作',
          type: 'warning'
        });
        return;
      }
      
      this.fetchAnnouncementDetail(item.announcement_id, 'edit');
    },
    async fetchAnnouncementDetail(announcementId, action) {
      this.loading = true;
      try {
        console.log(`获取公告详情，ID: ${announcementId}`);
        const response = await axios.get(`https://smartsound.top/api/admin/v1/announcements?id=${announcementId}`);
        
        if (response.data.code === 0 && response.data.data.announcements && response.data.data.announcements.length > 0) {
          const detail = response.data.data.announcements[0];
          console.log('获取公告详情成功:', detail);
          
          if (action === 'edit') {
            this.processEditAnnouncement(detail);
          } else if (action === 'preview') {
            this.processPreviewAnnouncement(detail);
          }
        } else {
          this.$message.error(response.data.message || '获取公告详情失败');
          
          // API失败时，尝试从本地数据获取
          this.findLocalAnnouncementDetail(announcementId, action);
        }
      } catch (error) {
        console.error('获取公告详情失败:', error);
        this.$message.error('获取公告详情失败，尝试使用本地数据');
        
        // 在API失败时，尝试从本地数据获取
        this.findLocalAnnouncementDetail(announcementId, action);
      } finally {
        this.loading = false;
      }
    },
    processEditAnnouncement(detail) {
      this.isEditing = true;
      this.currentAnnouncementId = detail.announcement_id;
      
      console.log('编辑公告，ID:', detail.announcement_id);
      
      // 将字符串日期转换为Date对象
      const parseDate = (dateStr) => {
        if (!dateStr) return new Date();
        return new Date(dateStr.replace(/-/g, '/'));
      };
      
      const startDate = parseDate(detail.start_at);
      const endDate = parseDate(detail.end_at);
      
      this.announcementForm = {
        title: detail.title,
        content: detail.content,
        start_at: detail.start_at || '',
        end_at: detail.end_at || '',
        is_active: detail.is_active,
        priority: Number(detail.priority)
      };
      this.dateRange = [startDate, endDate];
      this.contentPreview = detail.content;
      this.showEditor = true;
    },
    processPreviewAnnouncement(detail) {
      // 设置预览内容
      this.contentPreview = detail.content;
      
      // 显示预览弹窗
      this.$alert(
        `<div class="announcement-preview">
          <h2>${detail.title}</h2>
          <div class="announcement-meta">
            <p>有效期: ${detail.start_at} 至 ${detail.end_at}</p>
            <p>优先级: ${this.getPriorityText(detail.priority)}</p>
            <p>状态: ${detail.is_active ? '启用' : '禁用'}</p>
            <p>创建人: ${detail.admin_name}</p>
            <p>创建时间: ${detail.create_at}</p>
            <p>更新时间: ${detail.update_at}</p>
          </div>
          <div class="announcement-content">${detail.content}</div>
        </div>`,
        '公告预览',
        {
          dangerouslyUseHTMLString: true,
          customClass: 'announcement-preview-dialog',
          confirmButtonText: '关闭'
        }
      );
    },
    async deleteContent(item) {
      // 如果是模拟数据，显示提示
      if (item.announcement_id && typeof item.announcement_id === 'string' && item.announcement_id.startsWith('mock-')) {
        this.$message({
          message: '演示环境不支持删除操作',
          type: 'warning'
        });
        return;
      }
      
      this.$confirm(`确定要删除公告 "${item.title}" 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          this.loading = true;
          console.log(`删除公告，ID: ${item.announcement_id}`);
          
          // 调用删除公告的API
          const response = await axios.delete(`https://smartsound.top/api/admin/v1/announcements/delete?id=${item.announcement_id}`);
          
          if (response.data.code === 0) {
            this.$message.success('删除成功');
            // 刷新列表
            this.fetchAnnouncements();
          } else {
            this.$message.error(response.data.message || '删除公告失败');
          }
        } catch (error) {
          console.error('删除公告失败:', error);
          this.$message.error('删除公告失败，请检查网络连接');
          
          // 在API失败时，本地删除该公告
          if (this.originalAnnouncements && this.originalAnnouncements.length) {
            const index = this.originalAnnouncements.findIndex(a => a.announcement_id === item.announcement_id);
            if (index !== -1) {
              this.originalAnnouncements.splice(index, 1);
              this.applyFrontendFilters();
              this.$message({
                message: '已在本地移除该公告',
                type: 'info'
              });
            }
          }
        } finally {
          this.loading = false;
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    refreshAnnouncements() {
      this.fetchAnnouncements();
    },
    onSearchInput() {
      // 实现输入防抖
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
      }
      this.searchTimer = setTimeout(() => {
        this.applyFilters();
      }, 500);
    },
    handleSearchClear() {
      // 清除搜索内容时立即应用
      this.searchQuery = '';
      this.applyFilters();
    },
    handleFilterChange() {
      console.log('筛选条件变更:', {
        searchQuery: this.searchQuery,
        statusFilter: this.statusFilter,
        priorityFilter: this.priorityFilter
      });
      
      // 筛选条件变更时立即应用
      this.applyFilters();
    },
    applyFilters() {
      this.currentPage = 1;
      
      // 显示正在搜索的提示
      const hasFilters = this.hasActiveFilters;
                        
      if (hasFilters) {
        this.$message({
          message: '正在搜索...',
          type: 'info',
          duration: 1000
        });
        
        // 保存到搜索历史
        this.saveSearchHistory();
      }
      
      // 使用API进行搜索和过滤
      this.fetchAnnouncements();
    },
    resetFilters() {
      this.searchQuery = '';
      this.statusFilter = null;
      this.priorityFilter = null;
      this.currentPage = 1;
      
      // 重置筛选条件后重新获取数据
      this.fetchAnnouncements();
      
      // 显示提示消息
      this.$message({
        message: '已重置所有筛选条件',
        type: 'info'
      });
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1; // 切换每页数量时重置到第一页
      this.fetchAnnouncements(); // 重新请求数据
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchAnnouncements(); // 重新请求数据
    },
    getPriorityText(priority) {
      const priorityMap = {
        0: '普通',
        1: '重要',
        2: '紧急'
      };
      return priorityMap[priority] !== undefined ? priorityMap[priority] : '未知';
    },
    getPriorityType(priority) {
      const typeMap = {
        0: 'info',
        1: 'warning',
        2: 'danger'
      };
      return typeMap[priority] !== undefined ? typeMap[priority] : '';
    },
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return '未设置';
      // 简单格式化，可以根据需要调整
      return dateTimeStr;
    },
    // 保存搜索历史
    saveSearchHistory() {
      // 只有当有搜索条件时才保存
      if (!this.hasActiveFilters) return;
      
      // 创建搜索历史记录
      const historyItem = {
        searchQuery: this.searchQuery,
        statusFilter: this.statusFilter,
        priorityFilter: this.priorityFilter,
        timestamp: new Date().getTime()
      };
      
      // 检查是否已存在相同的搜索
      const existingIndex = this.searchHistory.findIndex(item => 
        item.searchQuery === historyItem.searchQuery &&
        item.statusFilter === historyItem.statusFilter &&
        item.priorityFilter === historyItem.priorityFilter
      );
      
      // 如果已存在，则删除旧的
      if (existingIndex !== -1) {
        this.searchHistory.splice(existingIndex, 1);
      }
      
      // 添加到历史记录开头
      this.searchHistory.unshift(historyItem);
      
      // 限制历史记录数量为10条
      if (this.searchHistory.length > 10) {
        this.searchHistory = this.searchHistory.slice(0, 10);
      }
      
      // 保存到本地存储
      localStorage.setItem('announcementSearchHistory', JSON.stringify(this.searchHistory));
    },
    // 加载搜索历史
    loadSearchHistory() {
      const history = localStorage.getItem('announcementSearchHistory');
      if (history) {
        try {
          this.searchHistory = JSON.parse(history);
        } catch (e) {
          console.error('解析搜索历史失败:', e);
          this.searchHistory = [];
        }
      }
    },
    // 应用历史搜索
    applyHistorySearch(historyItem) {
      this.searchQuery = historyItem.searchQuery || '';
      this.statusFilter = historyItem.statusFilter || '';
      this.priorityFilter = historyItem.priorityFilter !== null ? historyItem.priorityFilter : null;
      
      this.showSearchHistory = false;
      
      // 在应用历史搜索时，让状态过滤触发API请求
      if (this.statusFilter !== '') {
        this.fetchAnnouncements();
      } else {
        // 如果没有状态过滤，只应用前端过滤
        this.applyFrontendFilters();
      }
    },
    // 删除单条搜索历史
    removeSearchHistory(index) {
      this.searchHistory.splice(index, 1);
      localStorage.setItem('announcementSearchHistory', JSON.stringify(this.searchHistory));
    },
    // 清空搜索历史
    clearSearchHistory() {
      this.$confirm('确定要清空所有搜索历史记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.searchHistory = [];
        localStorage.removeItem('announcementSearchHistory');
        this.showSearchHistory = false;
        this.$message({
          type: 'success',
          message: '搜索历史已清空'
        });
      }).catch(() => {
        // 取消清空操作
      });
    },
    // 保存原始数据以支持前端过滤
    storeOriginalData(data) {
      if (!data || !Array.isArray(data)) {
        console.warn('接收到无效的公告数据:', data);
        this.originalAnnouncements = [];
        this.contentList = [];
        this.pagination = {
          total: 0,
          totalPages: 0
        };
        return;
      }
      
      this.originalAnnouncements = data;
      console.log(`共加载 ${data.length} 条公告数据`);
      this.applyFrontendFilters();
    },
    // 应用前端过滤器 - 仅用于关键词搜索
    applyFrontendFilters() {
      if (!this.originalAnnouncements || !this.originalAnnouncements.length) {
        console.warn('没有原始数据可供过滤');
        this.contentList = [];
        return;
      }
      
      let filtered = [...this.originalAnnouncements];
      
      // 应用关键词过滤（本地过滤）
      if (this.searchQuery && this.searchQuery.trim()) {
        const keyword = this.searchQuery.trim().toLowerCase();
        filtered = filtered.filter(item => {
          if (!item) return false;
          return (
            (item.title && item.title.toLowerCase().includes(keyword)) || 
            (item.content && item.content.toLowerCase().includes(keyword))
          );
        });
        console.log(`关键词过滤后剩余: ${filtered.length}条`);
      }
      
      // 应用优先级过滤（本地过滤）
      if (this.priorityFilter !== null && this.priorityFilter !== undefined) {
        filtered = filtered.filter(item => Number(item.priority) === Number(this.priorityFilter));
      }
      
      // 更新过滤后的列表
      this.contentList = filtered;
      
      // 处理空结果情况
      this.handleEmptyResult();
    },
    // 处理数据为空的情况
    handleEmptyResult() {
      // 如果没有数据
      if (this.contentList.length === 0 && this.hasActiveFilters) {
        this.$message({
          message: '没有找到符合条件的公告',
          type: 'info'
        });
      }
    },
    // 从本地数据中查找公告详情
    findLocalAnnouncementDetail(announcementId, action) {
      if (!this.originalAnnouncements || !this.originalAnnouncements.length) return;
      
      const detail = this.originalAnnouncements.find(item => item.announcement_id === announcementId);
      if (detail) {
        console.log('从本地数据获取公告详情:', detail);
        
        if (action === 'edit') {
          this.processEditAnnouncement(detail);
        } else if (action === 'preview') {
          this.processPreviewAnnouncement(detail);
        }
      } else {
        this.$message.error('找不到该公告的详细信息');
      }
    }
  }
}
</script>

<style scoped>
.content-container {
  padding: 16px 5px;
  position: relative;
  margin-bottom: 80px;
}

/* 页面标题区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #1890ff, #722ed1);
  color: white;
  border-radius: 12px;
  padding: 32px 40px;
  margin-bottom: 35px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  position: relative;
}

.page-header::after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 50%;
  background: rgba(255, 255, 255, 0.1);
  transform: skewX(-20deg);
}

.header-content {
  z-index: 1;
}

.page-title {
  font-size: 28px;
  margin: 0 0 12px 0;
  font-weight: 600;
}

.page-description {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
  line-height: 1.6;
}

.page-actions {
  z-index: 1;
  display: flex;
  gap: 10px;
}

/* 行容器样式 */
.row-container {
  margin-bottom: 30px;
  position: relative;
  z-index: 0;
}

/* 卡片基本样式 */
.el-card {
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.03);
  transform: translate3d(0, 0, 0);
  will-change: transform;
  transition: all 0.3s;
}

.el-card:hover {
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
  z-index: 1;
  border-color: rgba(24, 144, 255, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  margin-right: 12px;
  color: #303133;
}

/* 编辑器卡片样式 */
.editor-card {
  margin-bottom: 30px;
}

.editor-actions {
  display: flex;
  gap: 10px;
}

.form-section {
  background-color: #f9fafc;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.form-item {
  margin-bottom: 22px;
}

.date-picker {
  width: 100%;
}

.priority-select {
  width: 100%;
}

.editor-wrapper {
  display: grid;
  grid-template-columns: 50% 50%;
  gap: 20px;
}

.editor-section, .preview-section {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 15px;
  min-height: 300px;
  max-height: 500px;
  overflow-y: auto;
}

.content-textarea {
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
  line-height: 1.5;
}

.preview-section {
  background-color: #fafafa;
}

.section-title {
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
  padding-bottom: 10px;
  border-bottom: 1px dashed #e0e0e0;
}

.preview-meta {
  margin: 10px 0 20px;
  padding: 10px;
  background-color: #f0f9eb;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
}

.meta-item {
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.preview-body {
  padding: 10px 0;
  line-height: 1.6;
  color: #303133;
}

.preview-title-text {
  margin-top: 0;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

/* 表格卡片样式 */
.table-card {
  margin-bottom: 30px;
}

.list-actions {
  display: flex;
  gap: 10px;
}

/* 筛选器样式 */
.filters-section {
  background-color: #f9fafc;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.filter-row {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.search-bar {
  display: flex;
  align-items: center;
  width: 100%;
  position: relative;
}

.search-group {
  width: 100%;
  display: flex;
  align-items: center;
}

.search-input {
  width: 100%;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
}

.clear-search {
  margin-right: 0;
  padding: 0;
  border: none;
}

.advanced-toggle {
  margin-left: 10px;
  display: flex;
  align-items: center;
  white-space: nowrap;
}

.toggle-icon {
  margin-left: 5px;
  transition: transform 0.3s;
}

.toggle-icon.is-active {
  transform: rotate(180deg);
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 15px;
  justify-content: flex-start;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 200px;
}

.filter-select {
  width: 150px;
}

.advanced-search {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 6px;
  border: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
}

.filter-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

/* 活跃筛选标签 */
.active-filters {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  padding: 10px;
  background-color: #f0f9ff;
  border-radius: 6px;
  border: 1px dashed #a0cfff;
}

.filter-hint {
  font-weight: 500;
  color: #606266;
}

.filter-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 搜索历史样式 */
.search-history-list {
  max-height: 300px;
  overflow-y: auto;
}

.search-history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
}

.search-history-item:hover {
  background-color: #f5f7fa;
}

.history-content {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

.history-text {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.history-keyword {
  font-weight: 500;
  color: #303133;
}

.history-filter {
  font-size: 12px;
  color: #606266;
  background-color: #f0f2f5;
  padding: 2px 6px;
  border-radius: 4px;
}

.empty-history {
  padding: 20px 0;
  text-align: center;
}

/* 空数据状态 */
.empty-data {
  padding: 30px 0;
}

.empty-actions {
  margin-top: 10px;
}

/* 分页控件 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 按钮样式 */
.el-button {
  border-radius: 4px;
  transition: all 0.3s;
}

.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 浮动操作区 */
.floating-actions {
  position: fixed;
  right: 24px;
  bottom: 24px;
  display: flex;
  align-items: center;
  z-index: 100;
}

.refresh-btn {
  margin-left: 0;
}

/* 底部安全区域 */
.bottom-safe-area {
  height: 60px;
  width: 100%;
  margin-top: 20px;
}

/* 公告预览样式 */
:deep(.announcement-preview-dialog) {
  min-width: 500px;
  max-width: 800px;
  border-radius: 8px;
  overflow: hidden;
}

:deep(.announcement-preview h2) {
  margin-top: 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  color: #303133;
  font-size: 18px;
}

:deep(.announcement-preview-dialog .el-message-box__header) {
  background-color: #409EFF;
  padding: 15px 20px;
}

:deep(.announcement-preview-dialog .el-message-box__title) {
  color: white;
  font-size: 16px;
}

:deep(.announcement-preview-dialog .el-message-box__headerbtn .el-message-box__close) {
  color: white;
}

:deep(.announcement-meta) {
  background-color: #f5f7fa;
  padding: 10px 15px;
  border-radius: 4px;
  margin: 15px 0;
  font-size: 14px;
  color: #606266;
}

:deep(.announcement-meta p) {
  margin: 5px 0;
  display: flex;
  align-items: center;
  gap: 5px;
}

:deep(.announcement-content) {
  padding: 10px 0;
  white-space: pre-wrap;
  line-height: 1.5;
  color: #303133;
  max-height: 300px;
  overflow-y: auto;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    padding: 24px;
  }
  
  .page-actions {
    margin-top: 20px;
    flex-wrap: wrap;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .editor-wrapper {
    grid-template-columns: 1fr;
  }
  
  .filter-row {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-group {
    width: 100%;
    margin-right: 0;
  }
  
  .filter-input, .filter-select {
    width: 100%;
  }
  
  .floating-actions {
    right: 16px;
    bottom: 16px;
  }
}

/* 表格样式 */
.announcement-table {
  margin: 10px 0;
  border-radius: 8px;
  overflow: hidden;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.date-range-column {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
  color: #909399;
}

.date-range-column .date-text {
  font-size: 12px;
  color: #606266;
}

.date-range-column .date-separator {
  color: #bfbfbf;
  font-size: 12px;
}

.create-time {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
}

.filter-label {
  font-weight: 500;
  color: #606266;
  white-space: nowrap;
}

.date-range.no-wrap {
  white-space: nowrap;
  gap: 8px;
}

.table-card .el-table {
  margin-left: 0 !important;
}

.valid-period-header {
  padding-left: 30px !important;
}
</style>